import {
  classicBeh
} from "../classic-beh.js"
const innerAudioContext = wx.createInnerAudioContext()

Component({
  behaviors: [classicBeh],
  /**
   * 组件的属性列表
   */
  properties: {
    musicUrl: {
      type: String,
      observer: function(newVal) {
        innerAudioContext.src = newVal
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    playing: false,
    playSrc: './images/player@playing.png',
    pauseSrc: './images/player@waitting.png'
  },

  attached:function(){
    wx.getStorage({
      key: 'music',
      success: res => {
        let localMusicUrl = res.data.musicUrl
        console.log("获取本地播放状态-->" + res.data.playing)
        console.log("获取本地播放Url-->" + res.data.musicUrl)
        if (localMusicUrl == this.properties.musicUrl){
            this.setData({
              playing: res.data.playing
            })
        }
      }
    })
    wx.onBackgroundAudioPlay(()=>{
      console.log("onBackgroundAudioPlay")
      wx.getStorage({
        key: 'music',
        success: res => {
          let localMusicUrl = res.data.musicUrl
          if (localMusicUrl == this.properties.musicUrl) {
            this.setData({
              playing: true
            })
          }
          wx.setStorage({
            key: "music",
            data: {
              playing: this.data.playing,
              musicUrl: localMusicUrl
            }
          })
        }
      })
      
    })
    wx.onBackgroundAudioPause(() => {
      console.log("onBackgroundAudioPause")
      wx.getStorage({
        key: 'music',
        success: res => {
          let localMusicUrl = res.data.musicUrl
          if (localMusicUrl == this.properties.musicUrl) {
            this.setData({
              playing: false
            })
          }
          wx.setStorage({
            key: "music",
            data: {
              playing: this.data.playing,
              musicUrl: localMusicUrl
            }
          })
        }
      })
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    clickPlay: function() {
  
      let playing = this.data.playing
      if (playing) {
        wx.pauseBackgroundAudio()
      } else {
        wx.playBackgroundAudio({
          dataUrl: this.properties.musicUrl,
        })
      }

      this.setData({
        playing: !playing
      })
      wx.setStorage({
        key: "music",
        data: {
          playing: this.data.playing,
          musicUrl: this.properties.musicUrl
        }
      })
      console.log("存储本地播放状态-->" + this.data.playing)
      console.log("存储本地播放Url-->" + this.properties.musicUrl)
    }
  }
})